<template>
  <div>
    <div style="display: flex;align-items: center;justify-content: center">
      <el-card style="width: 80%;margin-top: 40px">
        <div style="border-bottom: 1px solid #000000;padding-bottom: 10px">账户安全设置</div>
        <div style="margin-top: 20px;display: flex;justify-content: center">
          <div style="width: 50%">
            <el-form ref="formRef" :model="tableData" :rules="rules" label-width="80px" style="margin-top: 20px">
              <el-form-item label="原始密码" prop="password">
                <el-input show-password v-model="tableData.password" placeholder="原始密码"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input show-password v-model="tableData.newPassword" placeholder="新密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input show-password v-model="tableData.confirmPassword" placeholder="确认密码"></el-input>
              </el-form-item>
              <div style="text-align: center; margin-bottom: 20px">
                <el-button type="primary" @click="update">确认修改</el-button>
              </div>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name: "safecenter",
  data() {
    return {
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      tableData: {},
      rules: {
        password: [
          {required: true, message: '请输入原始密码', trigger: 'blur'},
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请输入确认密码', trigger: 'blur'},
          {validator: this.validatePassword, trigger: 'blur'}
        ]
      }
    }
  }
  ,
  methods: {
    validatePassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请确认密码'));
      } else if (value !== this.tableData.newPassword) {
        callback(new Error('确认密码错误'));
      } else {
        callback();
      }
    },

    update() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 验证通过，进行密码更新操作
          this.$request.post('user_change_password/', {
            "user_id": this.user.id,
            "old_password": this.tableData.password,
            "new_password": this.tableData.newPassword,
          }).then(res => {
            if (res.code === '200') {
              // 成功更新
              this.$message.success('保存成功');
              this.$router.push('/login');
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
  }
}
</script>

<style>
/deep/ .el-form-item__label {
  font-weight: bold;
}
</style>